package com.leps.nq.tx.controller;

import cn.hutool.core.util.ObjectUtil;
import com.leps.nq.bu.entity.BuPump;
import com.leps.nq.bu.service.IBuPumpService;
import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.tx.core.PlcReadWriteService;
import com.leps.nq.tx.entity.PumpEffectivePoint;
import com.leps.nq.tx.mapper.PumpEffectivePointMapper;
import com.leps.nq.tx.vo.PumpOpenCloseVo;
import com.leps.nq.tx.vo.PumpPointVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "泵开关操作接口")
@RestController
public class PumpOpenCloseController {
    @Autowired
    PumpEffectivePointMapper mapper;
    @Autowired
    IBuPumpService pumpService;
    @Autowired
    PlcReadWriteService plcReadWriteService;

    @PostMapping("/pump-open-close")
    @ApiOperation("发送开关泵指令")
    @Log(title = "开关泵", businessType = BusinessType.OTHER)
    public R openOrClose(@RequestBody PumpOpenCloseVo pumpOpenCloseVo) {
        final int pumpId = pumpOpenCloseVo.getPumpId();
        final String action = pumpOpenCloseVo.getAction();
        final int dataValue = 1;
        String successMsg = "open".equalsIgnoreCase(action) ? "泵开启成功" : "泵关闭成功";
        PumpPointVo vo = this.mapper.selectPumpPointVoByPumpId(pumpId);
        if (ObjectUtil.isEmpty(vo.getEffectivePoints())) {
            return RBuilder.error("泵没有设置点位");
        }
        PumpEffectivePoint pointOpen = vo.getEffectivePoints().stream().filter(p -> "泵启动操作".equals(p.getSpec())).findFirst().get();
        PumpEffectivePoint pointClose = vo.getEffectivePoints().stream().filter(p -> "泵关闭操作".equals(p.getSpec())).findFirst().get();
        final String dataType = "open".equalsIgnoreCase(action) ? pointOpen.getDataType() : pointClose.getDataType();
        final int dataAddress = "open".equalsIgnoreCase(action) ? pointOpen.getDataAddress() : pointClose.getDataAddress();
        boolean success = this.plcReadWriteService.write(vo, dataAddress, dataType, dataValue);
        if (success) {
            // update pump online status
            BuPump pump = new BuPump();
            pump.setPumpId(pumpId);
            pump.setOnlineStatus("open".equalsIgnoreCase(action) ? 1 : 0);
            this.pumpService.updateById(pump);
            return RBuilder.ok(successMsg);
        }
        return RBuilder.error("PLC连接失败，系统将自动重试。");
    }

    @PostMapping("/pump-setup-open-minutes/{pumpId}/{minutes}")
    @ApiOperation("设置泵开设定值（Min）")
    @Log(title = "设置泵开设定值", businessType = BusinessType.OTHER)
    public R setupOpenMinutes(@PathVariable int pumpId, @PathVariable int minutes) {
        PumpPointVo vo = this.mapper.selectPumpPointVoByPumpId(pumpId);
        if (ObjectUtil.isEmpty(vo.getEffectivePoints())) {
            return RBuilder.error("泵没有设置点位");
        }
        PumpEffectivePoint point = vo.getEffectivePoints().stream().filter(p -> "泵开设定值（Min）".equals(p.getSpec())).findFirst().get();
        final String dataType = point.getDataType();
        final int dataAddress = point.getDataAddress();
        final int dataValue = minutes;
        boolean success = this.plcReadWriteService.write(vo, dataAddress, dataType, dataValue);
        if (success) return RBuilder.ok("泵开设定值设置成功");
        return RBuilder.error("PLC连接失败，系统将自动重试。");
    }

    @PostMapping("/pump-setup-close-minutes/{pumpId}/{minutes}")
    @ApiOperation("设置泵关设定值（Min）")
    @Log(title = "设置泵关设定值", businessType = BusinessType.OTHER)
    public R setupCloseMinutes(@PathVariable int pumpId, @PathVariable int minutes) {
        PumpPointVo vo = this.mapper.selectPumpPointVoByPumpId(pumpId);
        if (ObjectUtil.isEmpty(vo.getEffectivePoints())) {
            return RBuilder.error("泵没有设置点位");
        }
        PumpEffectivePoint point = vo.getEffectivePoints().stream().filter(p -> "泵关设定值（Min）".equals(p.getSpec())).findFirst().get();
        final String dataType = point.getDataType();
        final int dataAddress = point.getDataAddress();
        final int dataValue = minutes;
        boolean success = this.plcReadWriteService.write(vo, dataAddress, dataType, dataValue);
        if (success) return RBuilder.ok("泵关设定值设置成功");
        return RBuilder.error("PLC连接失败，系统将自动重试。");
    }
}
